package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.activity.HospitalDq.MyAdapter;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**家庭成员选择
 * @author Administrator
 *
 */
public class UserFamilyActivity extends Activity {
	private ImageButton ks_preview = null;
	private ImageButton addButton =null;
	private ListView lv = null;

	private CustomProgressDialog proDialog;// 加载框
	private UserFamilyActivity oThis = this;

	private Intent mIntent = null;
	private Map<String, Object> map_user; // 医院map
	List<Map<String, Object>> list_user = new ArrayList<Map<String, Object>>();// 家庭成员list
	MyApplication myApp;

	private int preID = -1;
	private MyAdapter myAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.usesrfamily);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		// 确定view
		findView();

		// 初始化界面数据
		GetData();

		// 点击事件
		setOnClick();
	}

	private void GetData() {
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData() {
		try {
			Message msg = myHandler.obtainMessage();
			list_user.clear();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApp.getAccount()));
			ls.add(new BasicNameValuePair("delid", myApp.getCurrentuerid()==null?"":myApp.getCurrentuerid()));
			myApp.setCurrentuerid("");
			JSONObject json = HTTPGetTool.getTool().post(
					URLUtils.HOST + URLUtils.GETUSERLIST, ls);
			JSONArray jsonArr;
			if (json != null && !json.equals("")) {
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					
					JSONObject js = null;
					if (new JSONArray(json.getString("familyinfo")).length() > 0)
					{
						jsonArr = new JSONArray(json.getString("familyinfo"));
						for (int i = 0; i < jsonArr.length(); i++) {
							map_user = new HashMap<String, Object>();
							js = jsonArr.getJSONObject(i);
							map_user.put("userid", js.getString("id"));
							map_user.put("zsxm", js.getString("zsxm"));
							map_user.put("sfzh", js.getString("sfzh"));
							map_user.put("sjh", js.getString("sjh"));
							map_user.put("sex", js.getString("sex"));
							map_user.put("jzcard", js.has("jzcard")?(js.getString("jzcard")==null?"":js.getString("jzcard")):"");
							map_user.put("zystate", js.getString("zystate"));
							map_user.put("mzstate", js.getString("mzstate"));
							list_user.add(map_user);
						}
						msg.what = 0;
						msg.obj = list_user;
					}
					else
					{
						msg.what = -1;
						msg.obj = "暂未添加成员，请点击添加按钮添加！";
					}
					
				}
				else
				{
					msg.what = -1;
					msg.obj = "系统错误";
				}
	
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接错误！";
			}
			myHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					list_user = (List<Map<String, Object>>) msg.obj;
					if (myAdapter == null)
					{
						myAdapter = new MyAdapter(oThis);
					}
					myAdapter.setList(list_user);
					lv.setAdapter(myAdapter);
					myAdapter.notifyDataSetChanged();
					
					break;
				default:
					break;
			}
		};
	};


	class MyAdapter extends BaseAdapter {
		private List<Map<String, Object>> list;
		private LayoutInflater mLayoutInflater;

		MyAdapter(Context context) {
			mLayoutInflater = LayoutInflater.from(context);
		}

		public List<Map<String, Object>> getList() {
			return list;
		}

		public void setList(List<Map<String, Object>> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(
						R.layout.user_family_item, null);
				holder = new ViewHolder();
				holder.tv_id = (TextView) convertView.findViewById(R.id.user_id);
				holder.tv_mc = (TextView) convertView.findViewById(R.id.user_mc);
				holder.tv_xz = (TextView) convertView.findViewById(R.id.user_xzstate);
				holder.tv_del = (ImageButton) convertView.findViewById(R.id.user_del);
				holder.tv_sfzh = (TextView) convertView.findViewById(R.id.user_sfzh);
				holder.tv_sjh = (TextView) convertView.findViewById(R.id.user_sjh);
				holder.tv_sex = (TextView) convertView.findViewById(R.id.user_xb);
				holder.tv_jzcard = (TextView) convertView.findViewById(R.id.user_jzcard);
				holder.tv_statezy = (TextView) convertView.findViewById(R.id.user_statezy);
				holder.tv_statemz = (TextView) convertView.findViewById(R.id.user_statemz);
				holder.tv_mzstate = (TextView) convertView.findViewById(R.id.user_mzstate);
				holder.tv_zystate = (TextView) convertView.findViewById(R.id.user_zystate);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv_id.setText((CharSequence) list.get(position).get("userid"));
			holder.tv_mc.setText((CharSequence) list.get(position).get("zsxm"));
			if(null!=myApp.getHzxm()&&myApp.getHzxm().equals(list.get(position).get("zsxm").toString())){
				holder.tv_xz.setText("(当前成员)");
				// 设置删除事件 
				holder.tv_del.setOnClickListener(new View.OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						// TODO Auto-generated method stub

						Toast.makeText(oThis, "当前成员不能删除！", Toast.LENGTH_SHORT).show();

					}
				});
			}else{
				holder.tv_xz.setText("");
				// 设置删除事件
				holder.tv_del.setOnClickListener(new View.OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						showBackTip(list.get(position).get("userid").toString());

					}
				});
			}
			
			holder.tv_sfzh.setText((CharSequence) list.get(position).get("sfzh"));
			holder.tv_sjh.setText((CharSequence) list.get(position).get("sjh"));
			holder.tv_sex.setText((CharSequence) list.get(position).get("sex"));
			holder.tv_jzcard.setText((CharSequence) list.get(position).get("jzcard"));
			String zystate = list.get(position).get("zystate").toString();
			String mzstate = list.get(position).get("mzstate").toString();
			holder.tv_mzstate.setText(mzstate);
			holder.tv_zystate.setText(zystate);
//			1 没有匹配信息  2 都匹配
//			4手机号姓名都不匹配 5 手机号不匹配  6 患者姓名不匹配
			if (zystate.equals("2"))//住院匹配
			{
				holder.tv_statezy.setText("与住院登记信息相符");
			}else if(zystate.equals("1")){
				holder.tv_statezy.setText("身份证与住院登记不符");
			}else if(zystate.equals("4")){
				holder.tv_statezy.setText("姓名手机号与住院登记不符");
			}else if(zystate.equals("6")){
				holder.tv_statezy.setText("姓名与住院登记不符");
			}else if(zystate.equals("5")){
				holder.tv_statezy.setText("手机号与住院登记不符");
			}
			
			if (mzstate.equals("2"))//住院匹配
			{
				holder.tv_statemz.setText("与门诊登记信息相符");
			}else if(mzstate.equals("1")){
				holder.tv_statemz.setText("身份证与门诊登记不符");
			}else if(mzstate.equals("4")){
				holder.tv_statemz.setText("姓名手机号与门诊登记不符");
			}else if(mzstate.equals("6")){
				holder.tv_statemz.setText("姓名与门诊登记不符");
			}else if(mzstate.equals("5")){
				holder.tv_statemz.setText("手机号与门诊登记不符");
			}
			
			
			if(position%2==0){//偶数
				if (position == preID)
					convertView.setBackgroundColor(getResources().getColor(
    						R.color.listhead_color));
    			else
    				convertView.setBackgroundColor(getResources().getColor(
    						R.color.backgroundMYD));
            }else{//奇数
            	if (position == preID)//选中
            		convertView.setBackgroundColor(getResources().getColor(
							R.color.listhead_color));
				else
					convertView.setBackgroundColor(getResources().getColor(
							R.color.white_bg));
            }
			return convertView;
		}

	}

	public class ViewHolder {
		private TextView tv_id;
		private TextView tv_mc;
		private TextView tv_xz;
		private TextView tv_sfzh;
		private TextView tv_sjh;
		private TextView tv_sex;
		private TextView tv_jzcard;
		private TextView tv_statezy;
		private TextView tv_statemz;
		private TextView tv_mzstate;
		private TextView tv_zystate;
		private ImageButton tv_del;
	}

	private void setOnClick() {
		// 设置preview监听
		ks_preview.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				oThis.onBackPressed();

			}
		});
		
		// 设置添加成员事件
		addButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent(UserFamilyActivity.this,Registeruserinfo.class);
				intent.putExtra("user_id", "");
				intent.putExtra("user_mc", "");
				intent.putExtra("user_sfzh", "");
				intent.putExtra("user_sjh", "");
				intent.putExtra("user_xb", "");
				intent.putExtra("user_jzcard", "");
				startActivity(intent);
			}
		});

		// 设置下一级菜单
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				myAdapter.notifyDataSetChanged();
				TextView user_id = (TextView) arg1.findViewById(R.id.user_id);
				TextView user_mc = (TextView) arg1.findViewById(R.id.user_mc);
				TextView user_sfzh = (TextView) arg1.findViewById(R.id.user_sfzh);
				TextView user_sjh = (TextView) arg1.findViewById(R.id.user_sjh);
				TextView user_xb = (TextView) arg1.findViewById(R.id.user_xb);
				TextView user_jzcard = (TextView) arg1.findViewById(R.id.user_jzcard);
				
				Intent intent = new Intent(UserFamilyActivity.this,Registeruserinfo.class);
				intent.putExtra("user_id", user_id.getText().toString());
				intent.putExtra("user_mc", user_mc.getText().toString());
				intent.putExtra("user_sfzh", user_sfzh.getText().toString());
				intent.putExtra("user_sjh", user_sjh.getText().toString());
				intent.putExtra("user_xb", user_xb.getText().toString());
				intent.putExtra("user_jzcard", user_jzcard.getText().toString());
				startActivity(intent);
				preID = arg2;
			}
		});
	}

	private void findView() {
		mIntent = getIntent();
		lv = (ListView) this.findViewById(R.id.user_list);
		ks_preview = (ImageButton) this.findViewById(R.id.user_preview);
		addButton = (ImageButton) this.findViewById(R.id.addButton);
	}
	
	/**
	 * 显示删除提示框
	 */
	private void showBackTip(final String id)
	{
		final Dialog dialog = new Dialog(this, R.style.MyDialog);

		dialog.setContentView(R.layout.dialog);
		TextView tv_title = (TextView) dialog.findViewById(R.id.title);
		tv_title.setText("删除提示");

		TextView tv_message = (TextView) dialog.findViewById(R.id.message);
		tv_message.setText("确定要删除该成员信息吗？");

		Button left = (Button) dialog.findViewById(R.id.left);
		left.setText(R.string.buttonOK);
		left.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
				myApp.setCurrentuerid(id);
				GetData();
			}
		});

		Button right = (Button) dialog.findViewById(R.id.right);
		right.setText(R.string.buttonCancle);
		right.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();

			}
		});
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}
}
